import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import styles from './index.module.less';
import { Button, message, PageHeader, Popconfirm } from 'antd';
import React from 'react';

export default function Dev() {

    const [value, setValue] = React.useState<string>(window.localStorage.getItem('$MIC_DEV_CONFIG') || defaultCond);

    const [config, setConfig] = React.useState('');

    const save = React.useMemo(() => {
        return (
            <Button key="save" type="primary" onClick={() => {
                try {
                    // eslint-disable-next-line no-eval
                    eval(`(${config})`);
                } catch (error) {
                    message.error('格式错误请检查');
                }
                window.localStorage.setItem('$MIC_DEV_CONFIG', config);
            }} >保存</Button>
        )
    }, [config])

    /** 恢复默认 按钮 */
    const reset = React.useMemo(() => {
        return (
            <Popconfirm
                key="reset"
                title="你是否要回复默认配置?"
                onConfirm={() => { setValue(defaultCond) }}
            >
                <Button type="primary" danger >恢复默认</Button>
            </Popconfirm>
        )
    }, [])

    return (
        <div className={styles.dev} >
            <div className={styles.cont} >
                <PageHeader
                    className={styles.pageHeader}
                    title="本地开发配置"
                    subTitle="此的配置只会在本地生效"
                    extra={[save, reset]}
                />
                <div style={{ flex: 1 }} >
                    <CodeMirror
                        style={{ height: '100%' }}
                        value={value}
                        height="100%"
                        extensions={[javascript({ jsx: true })]}
                        onBlur={() => { setValue(config) }}
                        onChange={setConfig}
                    />
                </div>
            </div>
        </div>
    );
}

const defaultCond = `{
    // 是否启用
    // start: true,
    
    // 入口应用
    // main: 'default.local',

    // 默认应用
    apps: {
       // "default.local"：{ id: 'default.local', url: '//app.mic.com:3100' },
    },
}
`